﻿using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpSM
{
    public class Sm4Util
    {
        private static string ALGO = "SM4/ECB/PKCS7Padding";

        /// <summary>
        /// 基于SM4加密
        /// </summary>
        /// <param name="srcData">源数据</param>
        /// <param name="key">密钥 Hex（16进制）编码的字符</param>
        /// <returns>Hex（16进制）编码的字符</returns>
        public static string Encrypt(string srcData, string key)
        {
            byte[] keyBytes = HexUtils.decode(key);
            byte[] srcDataBytes = Encoding.UTF8.GetBytes(srcData);
            if (keyBytes.Length != 16) throw new ArgumentException("err key length");
            KeyParameter keyParam = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
            IBufferedCipher c = CipherUtilities.GetCipher(ALGO);
            c.Init(true, keyParam);
            return Hex.ToHexString(c.DoFinal(srcDataBytes));
        }

        /// <summary>
        /// 基于SM4解密
        /// </summary>
        /// <param name="encData">密文 Hex（16进制）编码的字符</param>
        /// <param name="key">密钥 Hex（16进制）编码的字符</param>
        /// <returns>原数据</returns>
        public static string Decrypt(string encData, string key)
        {
            byte[] keyBytes = HexUtils.decode(key);
            byte[] encDataBytes = HexUtils.decode(encData);
            if (keyBytes.Length != 16) throw new ArgumentException("err key length");
            KeyParameter keyParam = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
            IBufferedCipher c = CipherUtilities.GetCipher(ALGO);
            c.Init(false, keyParam);
            return Encoding.UTF8.GetString(c.DoFinal(encDataBytes));
        }
    }
}
